package com.missilike.core.utils;

import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class JPushUtils {

    @Autowired(required = false)
    private JPushClient jpushClient;


    /**
     * 推送所有平台 用于广播消息  用于管理员使用
     */
    public boolean sendPushAllMessage(String title, String content, Map<String, String> extrasMap) {
        //生成推送的内容
        PushPayload payload = buildPushObject_all_message(title, content, extrasMap, ArrayUtils.EMPTY_STRING_ARRAY);
        PushResult pushResult = sendPush(payload);
        if (pushResult != null) {
            return pushResult.error == null;
        }
        return false;
    }

    /**
     * 推送所有平台 用于广播消息  用于管理员使用
     */
    public boolean sendPushAllNotification(String title, String content, Map<String, String> extrasMap) {
        //生成推送的内容
        PushPayload payload = buildPushObject_all_notification(title, content, extrasMap, ArrayUtils.EMPTY_STRING_ARRAY);
        PushResult pushResult = sendPush(payload);
        if (pushResult != null) {
            return pushResult.error == null;
        }
        return false;
    }

    /**
     * 根据别名推送所有平台
     * 一次推送最多 1000 个。
     */
    public void sendPushAliasAllMessage(String title, String content, Map<String, String> extrasMap, String... alias) {
        //生成推送的内容
        PushPayload payload = buildPushObject_all_message(title, content, extrasMap, alias);
        sendPush(payload);
    }


    /**
     * 根据标签推送所有平台
     * 一次推送最多 20 个。
     */
    public void sendPushTagsAllMessage(String title, String content, Map<String, String> extrasMap,
                                       String... tags) {
        //生成推送的内容
        PushPayload payload = buildPushObject_all_tags_message(title, content, extrasMap, tags);
        sendPush(payload);
    }


    /**
     * 发送
     *
     * @param payload
     * @return
     */
    private PushResult sendPush(PushPayload payload) {
        try {
            PushResult result = jpushClient.sendPush(payload);
            jpushClient.close();
            return result;
        } catch (Exception e) {
            log.error("jpush error ： HTTP Status -=- {}", e.getMessage());
        }
        return null;
    }

    /**
     * 构建Android和IOS的自定义消息的推送通知对象
     */
    private PushPayload buildPushObject_all_message(String title, String content, Map<String, String> extrasMap,
                                                    String... alias) {
        String[] newAlias = removeArrayEmptyElement(alias);
        return PushPayload.newBuilder()
                //设置接受的平台
                .setPlatform(Platform.android_ios())
                //Audience设置为all，说明采用广播方式推送，所有用户都可以接收到
                .setAudience((null == newAlias || newAlias.length == 0) ? Audience.all() : Audience.alias(alias))
                .setMessage(Message.newBuilder()
                        .setTitle(title)
                        .setMsgContent(content)
                        .addExtras(extrasMap)
                        .build()
                ).build();
    }

    /**
     * 构建Android和IOS的通知
     */
    private PushPayload buildPushObject_all_notification(String title, String content, Map<String, String> extrasMap,
                                                         String... alias) {
        String[] newAlias = removeArrayEmptyElement(alias);
        JSONObject iosAlert=new JSONObject();
        iosAlert.put("title",title);
        iosAlert.put("body",content);
        return PushPayload.newBuilder()
                //设置接受的平台
                .setPlatform(Platform.android_ios())
                //Audience设置为all，说明采用广播方式推送，所有用户都可以接收到
                .setAudience((null == newAlias || newAlias.length == 0) ? Audience.all() : Audience.alias(alias))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(content)
                                .setTitle(title)
                                .addExtras(extrasMap)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(iosAlert.toJSONString())
                                .addExtras(extrasMap)
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)//true-推送生产环境 false-推送开发环境
                        .build())
                .build();
    }


    private PushPayload buildPushObject_all_tags_message(String title, String content, Map<String, String> extrasMap,
                                                         String... tags) {
        String[] newAlias = removeArrayEmptyElement(tags);
        return PushPayload.newBuilder()
                //设置接受的平台
                .setPlatform(Platform.android_ios())
                //Audience设置为all，说明采用广播方式推送，所有用户都可以接收到
                .setAudience((null == newAlias || newAlias.length == 0) ? Audience.all() : Audience.tag(tags))
                .setMessage(Message.newBuilder()
                        .setTitle(title)
                        .setMsgContent(content)
                        .addExtras(extrasMap)
                        .build()
                ).build();
    }


    private String[] removeArrayEmptyElement(String... strArray) {
        if (ArrayUtils.isEmpty(strArray)) {
            return null;
        }
        List<String> strList = new ArrayList<>();
        for (String str : strArray) {
            // 消除空格后再做比较
            if (null != str && !"".equals(str.trim())) {
                strList.add(str);
            }
        }
        // 若仅输入"",则会将数组长度置为0
        return (String[]) strList.toArray();
    }


}
